<?php

namespace app\store\model;

use think\Cache;
use think\Db;
use think\Model;

/**
 * 订单管理
 * Class Order
 * @package app\store\controller
 */
class Orders extends Model
{

    /**
     * 修改商品状态
     * @param $state
     * @return false|int
     */
    public static function init()
    {
        self::event('after_update', function ($orders) {

            if ($orders->order_status == 20 && $orders->pay_status == 2) {
                Cache::store('redis')->inc('order_total_today');
                //获取redis的销售额(元)
                $order_total_price_today = Cache::store('redis')->get('order_total_price_today');
                if( $order_total_price_today != null  ){
                    //获取redis的销售额(元)后与新的销售额(元)相加
                    $num = $order_total_price_today + $orders->order_price;
                    Cache::store('redis')->set('order_total_price_today',$num);
                }else{
                    //创建销售额(元)并赋值
                    Cache::store('redis')->set('order_total_price_today',$orders->order_price);
                }

                (new self())->OrdersPayment($orders->id);
            }
        });

        /**
         * 订单增加时自增
         */
        self::event('after_insert', function ($orders) {
            Cache::store('redis')->inc('order_total');
            Cache::store('redis')->inc('order_user_total');
        });

        /**
         * 订单软删除时自减
         */
        self::afterUpdate(function ($orders) {
            if( Cache::store('redis')->get('order_total') == 0 ){
                Cache::store('redis')->inc('order_total',0);
                Cache::store('redis')->inc('order_user_total',0);
            }else{
                Cache::store('redis')->dec('order_total');
                Cache::store('redis')->dec('order_user_total');
            }
        });
    }

    /**
     * 订单拆分增加到商户表
     * @param $id
     * @return false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function OrdersPayment($id){
        $orders = self::where('id',$id)->find();
        if( $orders['pay_status'] == 1 ){
            return false;
        }

        $array = $this->ticket($id);
        foreach ($array['OrderTicket'] as $data){
            //判断商品为1(单票)添加单票
            $type = isset($data['type']) ? $data['type'] : 0;
            if( $type == 1 ){
                $Merchant = new Merchant([
                    'order_no' => $array[0]['order_no'],
                    'transaction_no' => $array[0]['transaction_no'],
                    'user_id' => $array[0]['user_id'],
                    'store_user_id' => $data['merchant_id'],
                    'num' => $array[0]['num'],
                    'start_time' => $array[0]['start_time'],
                    'end_time' => $array[0]['end_time'],
                    'article_price' => $data['price'],
                    'ticket_ids' => $data['id'],
                    'order_status' => 200
                ]);
                $Merchant->save();
            } else if( $type == 2 ){
                foreach ($array['OrderTicket']['ticket'] as $list){
                    $Merchant = new Merchant([
                        'order_no' => $array[0]['order_no'],
                        'transaction_no' => $array[0]['transaction_no'],
                        'user_id' => $array[0]['user_id'],
                        'store_user_id' => $list['merchant_id'],
                        'num' => 1,
                        'start_time' => $array[0]['start_time'],
                        'end_time' => $array[0]['end_time'],
                        'article_price' => $list['price'],
                        'ticket_ids' => $list['id'],
                        'order_status' => 200
                    ]);
                    $Merchant->save();
                }
            }
        }
    }

    public function ticket($id){
        $ticket = Db::name('orders')->alias('orders')
            ->where('orders.id',$id)
            ->join('user', 'user.user_id = orders.user_id')
            ->join('OrderTicket', 'OrderTicket.id = orders.ticket_ids')
            ->order(['orders.create_time' => 'desc'])
            ->select();
        foreach ($ticket as $list){
            $ticket['OrderTicket'] = Db::name('OrderTicket')->where(
                'OrderTicket.id', 'in' ,$list['ticket_ids']
            )->alias('OrderTicket')
                ->join('ticket', 'ticket.id = OrderTicket.ticket_id')
                ->join('StoreUser', 'ticket.store_user_id = StoreUser.merchant_id')
                ->select();
        }
        foreach ($ticket['OrderTicket'] as $data){
            if( $data['type'] == 2  ){
                $ticket['OrderTicket']['ticket'] = Db::name('ticket')->where(
                    'ticket.id', 'in' ,$data['ticket_set']
                )->alias('ticket')
                    ->join('StoreUser', 'ticket.store_user_id = StoreUser.merchant_id')
                    ->select();
            }
        }
        return $ticket;
    }

    /**
     * 订单列表
     * @param string $dataType
     * @param array $query
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($dataType, $query = [])
    {
        // 检索查询条件
        !empty($query) && $this->setWhere($query);
        $list = Db::name('orders')->order(['create_time' => 'desc'])
            ->where($this->transferDataType($dataType))
            ->where('is_delete', '=', 0)
            ->paginate(10, false, [
                'query' => \request()->request()
            ]);
        return $list;
    }

    public function list($id){
        $ticket = Db::name('orders')
            ->alias('orders')
            ->where('orders.id',$id)
            ->join('user', 'user.user_id = orders.user_id')
            ->order(['orders.create_time' => 'desc'])
            ->where('orders.is_delete', '=', 0)
            ->select();
        foreach ($ticket as $list){
            $ticket['OrderTicket'] = Db::name('OrderTicket')->where(
                'OrderTicket.id', 'in' ,$list['ticket_ids']
            )->alias('OrderTicket')
                ->join('ticket', 'ticket.id = OrderTicket.ticket_id')
                ->join('StoreUser', 'ticket.store_user_id = StoreUser.merchant_id')
                ->join('scenic','ticket.scenic_id = scenic.id')
                ->join('UploadFile' , 'UploadFile.file_id = scenic.logo_image_id')
                ->field('OrderTicket.id,file_name,ticket.name,price,num,user_name,ticket.type,content')
                ->select();
        }
        return $ticket;
    }

    /**
     * 订单列表详情
     * @param $id
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function detail($id){
        $data = $this->alias('orders')
            ->where('orders.id',$id)
            ->join('user', 'user.user_id = orders.user_id')
            ->join('OrderTicket', 'OrderTicket.id = orders.ticket_ids')
            ->join('ticket', 'ticket.id = OrderTicket.ticket_id')
            ->join('scenic','ticket.scenic_id = scenic.id')
            ->join('UploadFile' , 'UploadFile.file_id = scenic.logo_image_id')
            ->where('orders.is_delete', '=', 0)
            ->paginate(10, false, [
                'query' => \request()->request()
            ]);
        return $data;
    }

    private function setWhere($query)
    {
        if (isset($query['start_time']) && !empty($query['start_time'])) {
            $this->where('orders.start_time', '>=', strtotime($query['start_time']));
        }
        if (isset($query['end_time']) && !empty($query['end_time'])) {
            $this->where('orders.end_time', '<', strtotime($query['end_time']) + 86400);
        }
        // 用户id
        if (isset($query['user_id']) && $query['user_id'] > 0) {
            $this->where('orders.user_id', '=', (int)$query['user_id']);
        }
    }

    private function transferDataType($dataType)
    {
        // 数据类型
        $filter = [];
        switch ($dataType) {
            case 'all':
                $filter = [];
                break;
            case 'pay':
                $filter = ['order_status' => 10];
                break;
            case 'cancelled':
                $filter = ['order_status' => 11];
                break;
            case 'inspect':
                $filter = ['order_status' => 20];
                break;
            case 'PaidCancellation':
                $filter = ['order_status' => 21];
                break;
            case 'complete':
                $filter = ['order_status' => 80];
                break;
        }
        return $filter;
    }

}